package com.sskj.fabi.ui.fragment;


import android.support.design.widget.BottomSheetDialog;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.fabi.R;
import com.sskj.fabi.R2;
import com.sskj.fabi.bean.BuySellBean;
import com.sskj.fabi.bean.OrderDetailBean;
import com.sskj.fabi.bean.PayWayItem;
import com.sskj.fabi.component.DaggerUserDataComponent;
import com.sskj.fabi.presenter.BuySellFragmentPresenter;
import com.sskj.fabi.util.TipFabiUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.bean.enums.CoinEnum;
import com.sskj.lib.bean.enums.PayTypeEnum;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.mvchelper.ModelRx2DataSource;
import com.sskj.lib.util.AppCircleCheckUtil;
import com.sskj.lib.util.CoinUtil;
import com.sskj.lib.util.NumberUtil;
import com.sskj.lib.util.StringUtil;
import com.sskj.lib.util.TipUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

@Route(path = RConfig.FABI_FRAGMENT_BUY_SELL)
public class BuySellFragment extends BaseFragment<BuySellFragmentPresenter> {
    @Autowired
    boolean isBuy;  // true 购买大厅  false 出售大厅
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;

    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    private SlimAdapter slimAdapter;
    private int curPos;
    private BottomSheetDialog orderSheet;
    private MVCCoolHelper<List<BuySellBean.ListBean>> mvcHelper;
    private List<PayWayItem> listPay;  // 当前用户支付方式

    @Override
    protected int getLayoutId() {
        return R.layout.fabi_fragment_buy_sell;
    }

    @Override
    public BuySellFragmentPresenter getPresenter() {
        return new BuySellFragmentPresenter();
    }

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                mPresenter.requsetPayWayList();
            } else {
                userData = null;
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setLeftPadding((int) RudenessScreenHelper.pt2px(App.INSTANCE, 30))
                .setRightPadding((int) RudenessScreenHelper.pt2px(App.INSTANCE, 30))
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 1))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.transparent))
        );
        // 剩余数量
        slimAdapter = SlimAdapter.create().register(R.layout.fabi_recy_item_buy_sell, new SlimInjector<BuySellBean.ListBean>() {
            @Override
            public void onInject(BuySellBean.ListBean data, IViewInjector injector, List payloads) {
                injector.clicked(R.id.item_ll, v -> {
                    curPos = slimAdapter.getData().indexOf(data);
                    trade();
                }).text(R.id.tvName, data.getUsername())
                        .text(R.id.tvDealNum, App.INSTANCE.getString(R.string.fabibuySellFragment1) + " " + CoinUtil.keepUSDT(data.getDealsNum()))
                        .text(R.id.tvPercent, App.INSTANCE.getString(R.string.fabibuySellFragment2) + " " + ((data.getComplete() + data.getCancle()) == 0 ? 0 : NumberUtil.keepMax2(100 * data.getComplete() / (data.getComplete() + data.getCancle()))) + "%")
                        .text(R.id.tv_num, App.INSTANCE.getString(R.string.fabitipFabiUtil5) + "  " + CoinUtil.keepCoinNum(CoinEnum.USDT.getCode(), data.getTransNum()) + " USDT")  // 剩余数量
                        .text(R.id.tvLimitMoney, App.INSTANCE.getString(R.string.fabibuySellFragment4) + "  " + data.getMinPrice() + "-" + data.getMaxPrice() + " CNY")
                        .text(R.id.tv_china_money, App.INSTANCE.getString(R.string.fabibuySellFragment5) + "  " + data.getPrice() + " CNY")
                        .text(R.id.tvPhoto, StringUtil.getFirstName(data.getUsername()))
                        .text(R.id.btSale, isBuy ? App.INSTANCE.getString(R.string.fabibuySellFragment6) : App.INSTANCE.getString(R.string.fabibuySellFragment7))
                        .visibility(R.id.iv_wechat, data.getPayType().contains("1") ? View.VISIBLE : View.GONE)
                        .visibility(R.id.iv_bank, data.getPayType().contains("3") ? View.VISIBLE : View.GONE)
                        .visibility(R.id.iv_alipay, data.getPayType().contains("2") ? View.VISIBLE : View.GONE)
                        .background(R.id.btSale, isBuy ? R.drawable.fabi_solid_ff5_bg : R.drawable.fabi_solid_03c_bg)
                ;
            }
        });
        slimAdapter.attachTo(recyclerView).updateData(new ArrayList());
        ModelRx2DataSource<BuySellBean.ListBean> dataSource = new ModelRx2DataSource<>((ModelRx2DataSource.OnLoadSource<BuySellBean.ListBean>)
                page -> mPresenter.getData(page + "", 20 + "", isBuy), 20);
        mvcHelper = new MVCCoolHelper<>(coolRefreshView);
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(slimAdapter);

        mvcHelper.refresh();
    }

    private void trade() {
        if (!AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
            return;
        }
        BuySellBean.ListBean dataItem = (BuySellBean.ListBean) slimAdapter.getDataItem(curPos);
        if (SPUtil.get(SPConfig.ID, "").equals(dataItem.getStockUserId())) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.fabibuySellFragment8));
            return;
        }
//        if (!AppCircleCheckUtil.checkTradePwd(getActivity(), userData)) {
//            return;
//        }

        if (!isBuy) { //出售大厅高级认证判断

            if (!AppCircleCheckUtil.checkTradePwd(getActivity(), userData)) {  // 资金密码
                return;
            }

            if (!checkPayMatch(listPay, dataItem)) {
                return;
            }
        }
        showSell();
    }

    private void showSell() {
        BuySellBean.ListBean dataItem = (BuySellBean.ListBean) slimAdapter.getDataItem(curPos);
        orderSheet = TipFabiUtil.showTrade(getActivity(), isBuy,
                dataItem.getPrice(),
                dataItem.getMinPrice(),
                dataItem.getMaxPrice(),
                dataItem.getTransNum(),
                str -> {
                    mPresenter.order(str[2], dataItem.getEntrustNo(), str[0], isBuy, dataItem.getMinPrice(), dataItem.getMaxPrice(), str[3], str[1], dataItem.getPrice());
                });
        orderSheet.show();
    }

    public void orderSuccess(OrderDetailBean orderDetailBean) {
        if (orderSheet != null && orderSheet.isShowing()) {
            orderSheet.dismiss();
        }
        if (mvcHelper != null) {
            mvcHelper.refresh();
        }
        ARouter.getInstance().build(RConfig.FABI_ORDER_RECORD_DETAIL)
                .withString(Constans.ORDER_NUM, orderDetailBean.getDealEntrustNo())
                .withBoolean(Constans.IS_BUYER, isBuy)
                .navigation();

    }

    // 记录用户支付方式
    public void updateUi(List<PayWayItem> listPay) {
        this.listPay = listPay;
    }

    @Override
    public void onResume() {

        super.onResume();
        if (mPresenter != null && userData != null) {
            mPresenter.requsetPayWayList();
        }
    }

    //检测用户支付方式是否匹配的上买家支付方式
    public boolean checkPayMatch(List<PayWayItem> payList, BuySellBean.ListBean bean) {
        StringBuffer sbText = new StringBuffer();
        if (payList == null) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.fabibuySellFragment9));
            mPresenter.requsetPayWayList();

            return false;
        }
        if (bean.getPayType().contains(PayTypeEnum.ALIPAY.getType())) {  // 买家有支付宝
            sbText.append("、" + App.INSTANCE.getString(R.string.fabipublishActivity26));
            for (int i = 0; i < payList.size(); i++) {
                if (payList.get(i).getPayType() == 2 && !payList.get(i).isStatus()) {  //卖家有支付宝
                    return true;
                }
            }
        }
        if (bean.getPayType().contains(PayTypeEnum.WX.getType())) { // 买家有微信
            sbText.append("、" + App.INSTANCE.getString(R.string.fabipayWayBean2));
            for (int i = 0; i < payList.size(); i++) {
                if (payList.get(i).getPayType() == 1 && !payList.get(i).isStatus()) {  //卖家有微信
                    return true;
                }
            }
        }
        if (bean.getPayType().contains(PayTypeEnum.BANK.getType())) { // 买家有银行卡
            sbText.append("、" + App.INSTANCE.getString(R.string.fabibuySellFragment12));
            for (int i = 0; i < payList.size(); i++) {
                if (payList.get(i).getPayType() == 3 && !payList.get(i).isStatus()) {  //卖家有微信
                    return true;
                }
            }
        }
        TipUtil.getSureCancelTip(getActivity(), App.INSTANCE.getString(R.string.fabipublishActivity2), String.format(App.INSTANCE.getString(R.string.fabibuySellFragment14), sbText.substring(1)), App.INSTANCE.getString(R.string.fabibuySellFragment15), () -> {
            ARouter.getInstance().build(RConfig.MINE_SECURITY_CENTER).navigation();
        });
        return false;
    }

    @Subscribe(code = RxBusCode.PUBLISH_SUCCESS, threadMode = ThreadMode.MAIN)
    public void refresh() {
        mvcHelper.refresh();
    }
}

